package controllers;

import beans.LocalizedBean;
import connectivity.Dbmanager;
import connectivity.QueryManager;
import java.io.*;
import java.net.*;
import java.util.LinkedList;
import javax.servlet.*;
import javax.servlet.http.*;
import models.Course;
import models.DigitalClass;
import models.DigitalClassSession;

public class SubscribeToDigitalClassController extends HttpServlet {
    private Dbmanager dbManager;
    private QueryManager queryManager;
    
    
    /*
     * HTTP GET Request
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        dbManager = new Dbmanager();
        dbManager.openConnection();
        queryManager = new QueryManager(dbManager); 
        HttpSession sessie = request.getSession(); 
        
        if(isInteger(request.getParameter("ID"))){
            queryManager.addSubscribedDigitalClass(Integer.parseInt(sessie.getAttribute("userId").toString()), Integer.parseInt(request.getParameter("ID")));
            request.setAttribute("melding", "U bent succesvol ingeschreven voor deze digital class");        
        } 
        LinkedList<DigitalClass> digitalClasses = queryManager.getAllDigitalClasses();
        LinkedList<Integer> subscribedCourses =  queryManager.getallsubscribedcoursesbyid(Integer.parseInt(sessie.getAttribute("userId").toString()));
        boolean courseSubscribed;

        for(DigitalClass currentDigitalClass : digitalClasses){ 
                if(!sessie.getAttribute("userLevel").toString().equals("3")){
                    courseSubscribed = false;
                    for(Integer courseID : subscribedCourses){
                        if(currentDigitalClass.getCourse().getCourseID() == courseID){
                            courseSubscribed = true;
                        }
                    }
                    if(courseSubscribed == false){ 
                        digitalClasses.remove(currentDigitalClass);
                    }
                }    
        }        

        request.setAttribute("digitalClasses", digitalClasses);            
        
        
        String address = "/subscribe_to_digitalclass.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);       
        
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
     
    }    
    


    public static boolean isInteger(String s) {
        try { 
            Integer.parseInt(s); 
        } catch(NumberFormatException e) { 
            return false; 
        }
        // only got here if we didn't return false
        return true;
    }    
}